package com.ruoyi.web.controller.fenxi;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.PropertiesUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.fenxi.response.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.RModel;
import com.ruoyi.system.service.IRModelService;
import com.ruoyi.web.controller.fenxi.utils.CmdUtils;
import com.ruoyi.web.controller.fenxi.utils.ImportUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 模型管理Controller
 *
 * @author ruoyi
 * @date 2022-09-25
 */
@Controller
@RequestMapping("/system/model")
public class RModelController extends BaseController
{
    private String prefix = "system/model";

    @Autowired
    private IRModelService rModelService;

    @RequiresPermissions("system:model:view")
    @GetMapping()
    public String model()
    {
        return prefix + "/model";
    }

    @GetMapping("/preview")
    public String preview(Long id,ModelMap mmap)
    {

        RModel rModel = rModelService.selectRModelById(id);
        mmap.put("previewUrl", rModel.getUrl());
        return prefix + "/preview";
    }

    /**
     * 查询模型管理列表
     */
    @RequiresPermissions("system:model:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RModel rModel)
    {
        startPage();
        List<RModel> list = rModelService.selectRModelList(rModel);
        return getDataTable(list);
    }

    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(RModel rModel)
    {
        startPage(1,20);
//        List<RModel> list = (List<RModel>) CacheUtils.get(CacheUtils.MODEL_KEY);
//        if(Objects.isNull(list)||list.isEmpty()){
//            list = rModelService.selectRModelList(rModel);
//            CacheUtils.put(CacheUtils.MODEL_KEY,list);
//        }
        List<RModel>  list = rModelService.selectRModelList(rModel);
        return getDataTable(list);
    }

    /**
     * 导入完成后进行解析
     * @return
     * @throws Exception
     * http://localhost:8080/admin/images/images/20180918/180005766869a9.xls
     */
    @RequestMapping("/import")
    @ResponseBody
    public R importsave (@RequestBody RModel rModel) {
        rModelService.insertRModel(rModel);

        String turl = rModel.getPath();
        String curl = rModel.getCondaPath();
        String start_name = rModel.getStartName();
        String code = rModel.getCode();
        try {
            Long userId = ShiroUtils.getUserId();
            String root = PropertiesUtils.getInstance().get("file_path");
            String path = root + turl.substring(turl.indexOf("/images/") + 8);
            String conda_path = root + curl.substring(turl.indexOf("/images/") + 8);
            ImportUtil.getInstance().import2DB(rModel.getId(), userId, path, conda_path, start_name, code);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败, 请重新导入！");
        }
        return R.ok();
    }


    /**
     * 启动服务
     */
    @RequestMapping("/start/{id}")
    @ResponseBody
    public R start(@PathVariable("id") Long id) {
        upDateStatus(id);
        String root = PropertiesUtils.getInstance().get("file_path");

        RModel rModel = rModelService.selectRModelById(id);

        String cmd = "bash " + root + "/" + rModel.getProjName() + "/start.sh" ;
        Boolean seccess = CmdUtils.processCMD(cmd);

        if (seccess) {
            rModel.setRunStatus(2);
        } else {
            rModel.setRunStatus(3);
        }
        rModelService.updateRModel(rModel);
        return R.ok().put("rModel", rModel);
    }
    public void upDateStatus(Long id){
        RModel rModel = new RModel();
        rModel.setId(id);
        rModel.setRunStatus(1);
        rModelService.updateRModel(rModel);
    }
    /**
     * 停止服务
     */
    @RequestMapping("/stop/{id}")
    @ResponseBody
    public R stop(@PathVariable("id") Long id) {
        upDateStatus(id);
        String root = PropertiesUtils.getInstance().get("file_path");

        RModel rModel = rModelService.selectRModelById(id);

        String cmd = "bash " + root + "/" + rModel.getProjName() + "/shutdown.sh" ;
        Boolean seccess = CmdUtils.processCMD(cmd);

        if (seccess) {
            rModel.setRunStatus(0);
        } else {
            rModel.setRunStatus(3);
        }
        rModelService.updateRModel(rModel);
        return R.ok().put("rModel", rModel);
    }


    /**
     * 导出模型管理列表
     */
    @RequiresPermissions("system:model:export")
    @Log(title = "模型管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RModel rModel)
    {
        List<RModel> list = rModelService.selectRModelList(rModel);
        ExcelUtil<RModel> util = new ExcelUtil<RModel>(RModel.class);
        return util.exportExcel(list, "模型管理数据");
    }

    /**
     * 新增模型管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存模型管理
     */
    @RequiresPermissions("system:model:add")
    @Log(title = "模型管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RModel rModel)
    {
        CacheUtils.remove(CacheUtils.MODEL_KEY);
        int i = 0;
        try {
            if(StringUtils.isNotEmpty(rModel.getDefaultCondaPath())){
                rModel.setCondaPath(rModel.getDefaultCondaPath());
            }
            R importsave = importsave(rModel);
            if(importsave.get("code").equals(0)){
                i = 1;
            }
        }catch (Exception e){
            logger.error("添加模型失败"+e);
        }
        return toAjax(i);
    }

    /**
     * 修改模型管理
     */
    @RequiresPermissions("system:model:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        RModel rModel = rModelService.selectRModelById(id);
        mmap.put("rModel", rModel);
        return prefix + "/edit";
    }

    /**
     * 修改保存模型管理
     */
    @RequiresPermissions("system:model:edit")
    @Log(title = "模型管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RModel rModel)
    {
        CacheUtils.remove(CacheUtils.MODEL_KEY);
        if(StringUtils.isNotEmpty(rModel.getDefaultCondaPath())){
            rModel.setCondaPath(rModel.getDefaultCondaPath());
        }
        return toAjax(rModelService.updateRModel(rModel));
    }


    /**
     * 删除模型管理
     */
    @RequiresPermissions("system:model:remove")
    @Log(title = "模型管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        CacheUtils.remove(CacheUtils.MODEL_KEY);
        return toAjax(rModelService.deleteRModelByIds(ids));
    }
}
